package com.kuwei.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.kuwei.base.ParamerException;
import com.kuwei.base.ServiceException;
import com.kuwei.model.User;
import com.kuwei.mybatis.pages.PageMap;
import com.kuwei.service.ProcedureService;
import com.kuwei.servlet.frame.BaseServlet;
import com.kuwei.utils.CommonUtils;
import com.kuwei.utils.Constants;
import com.kuwei.utils.ReturnResult;
import com.kuwei.utils.ServiceConstants;
import com.kuwei.utils.SessionUtils;
import com.kuwei.utils.Utility;

@Service("procedureServlet")
public class ProcedureServlet extends BaseServlet{

	@Autowired
	public ProcedureService procedureService;
	
	private static final Logger logger = LoggerFactory.getLogger(ProcedureServlet.class);
	
	public void getProceList(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String,Object> reqMap = new HashMap<String, Object>();
		try {
			User user = SessionUtils.getUserInfo(request);
			List<Map<String, Object>> list = null;
			reqMap.put("STATUS_CD", Constants.STATE_1000);
			String prod_id = request.getParameter("PROD_ID");
			//管理员账号登录时
			if(Constants.ADMIN_CODE.equals(user.getType())){
				String user_id = request.getParameter("USER_ID");
				if(!CommonUtils.isEmpty(user_id)){
					//根据用户id查询用户对应的工序
					reqMap.put("USER_ID", user_id);
//					list =  procedureService.queryUserProcedure(reqMap);
					if(!CommonUtils.isEmpty(prod_id)){
						reqMap.put("PROD_ID", prod_id);
						list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PRODUCT_USER_PROCEDURE,reqMap);
					} else{
						list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_USER_PROCEDURE,reqMap);
					}
				} else{
					if(!CommonUtils.isEmpty(prod_id)){
						reqMap.put("PROD_ID", prod_id);
						list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PRODUCT_PROCEDURE,reqMap);
					} else{
						//查询所有工序
						list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PROCEDURE,reqMap);
					}
				}
			} else{
				//查询当前登录用户对应的工序
				reqMap.put("USER_ID", user.getUser_id());
				if(!CommonUtils.isEmpty(prod_id)){
					reqMap.put("PROD_ID", prod_id);
					list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PRODUCT_USER_PROCEDURE,reqMap);
				} else{
					list =  sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_USER_PROCEDURE,reqMap);
				}
			}
				
			result.setContent(Constants.SUCCESS, null,list);
		} catch (Exception e){
			result.setContent(Constants.FAIL, e.getMessage());
		} 
		rtnMap.put("data", result.getContent());
	}
	
	/**
	 * 新增工序
	 * @param request
	 * @param response
	 * @param rtnMap
	 * @throws ServiceException
	 * @throws ParamerException
	 */
	public void addProce(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		if(!CommonUtils.isEmpty(param.get("PRO_NAME"))&&!CommonUtils.isEmpty(param.get("PRO_CODE"))
				&&!CommonUtils.isEmpty(param.get("PRICE"))&&!CommonUtils.isEmpty(SessionUtils.getUserInfo(request).getUser_id())){
			reqMap.putAll(param);
			reqMap.put("STATUS_CD", "1000");
			reqMap.put("CREATE_USER", SessionUtils.getUserInfo(request).getUser_id());
			try {
				if(procedureService.insertProcedure(reqMap)>0){
					result.setContent(Constants.SUCCESS, "新增工序成功");
				}
				else{
					result.setContent(Constants.FAIL, "新增工序失败");
				}
			} catch (ServiceException e) {
				result.setContent(Constants.FAIL, e.getMessage());
				throw new ServiceException(this.getClass().toString()+" \n ->"+e.getMessage(),e);
			} catch (Exception e){
				result.setContent(Constants.FAIL, e.getMessage());
			}
		} else{
			throw new ParamerException("Parameter[PRO_ID/PRO_NAME/PRO_CODE/PRICE] is empty, please check it!");
		}
		
		rtnMap.put("data", result.getContent());
	}
	
	/**
	 * 查询工序数量信息
	 * @param request
	 * @param response
	 * @param rtnMap
	 * @throws ServiceException
	 * @throws ParamerException
	 */
	public void getProceNumList(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		User user = SessionUtils.getUserInfo(request);
		PageMap pm = new PageMap();
		List<Map<String, Object>> list = null;
		if(!CommonUtils.isEmpty(user.getUser_id())){
//			reqMap.putAll(param);
			//管理员用户登录时，user_id为默认选项值-1，查询所有员工数据
			if(Constants.ADMIN_CODE.equals(user.getType())){
				String user_id = (String) param.get("USER_ID");
				//若user_id不为空且不为默认选项值-1，则根据user_id查询否则user_id设为null
				if(!CommonUtils.isEmpty(user_id)&&!Constants.DEFAULT_ITEM.equals(user_id)){
					reqMap.put("USER_ID", user_id);
				} else{
					reqMap.put("USER_ID", null);
				}
				
			} else{
				//非管理员用户则根据当前用户查询
				reqMap.put("USER_ID", user.getUser_id());
			}
			//工序id
			String pro_id = (String) param.get("PRO_ID");
			if(!CommonUtils.isEmpty(pro_id)&&!Constants.DEFAULT_ITEM.equals(pro_id)){
				reqMap.put("PRO_ID", pro_id);
			} else{
				reqMap.put("PRO_ID", null);
			}
			//产品id
			String prod_id = (String) param.get("PROD_ID");
			if(!CommonUtils.isEmpty(prod_id)&&!Constants.DEFAULT_ITEM.equals(pro_id)){
				reqMap.put("PROD_ID", prod_id);
			} else{
				reqMap.put("PROD_ID", null);
			}
			
			//产品状态
			String prod_status_cd = (String) param.get("PROD_STATUS_CD");
			if(!CommonUtils.isEmpty(prod_status_cd)&&!Constants.DEFAULT_ITEM.equals(prod_status_cd)){
				reqMap.put("PROD_STATUS_CD", prod_status_cd);
			} else{
				reqMap.put("PROD_STATUS_CD", null);
			}
			
			//时间
			String begin_date = (String) param.get("BEGIN_DATE");
			if(!CommonUtils.isEmpty(begin_date)){
				reqMap.put("BEGIN_DATE", begin_date);
			} else{
				reqMap.put("BEGIN_DATE", null);
			}
			String end_date = (String) param.get("END_DATE");
			if(!CommonUtils.isEmpty(end_date)){
				reqMap.put("END_DATE", end_date);
			} else{
				reqMap.put("END_DATE", null);
			}
			
			pm.putAll(reqMap);
			String pageSize = request.getParameter("pageSize");
			if(CommonUtils.isEmpty(pageSize)){
				pageSize = "10";
			}
			
			String startNum = request.getParameter("startNum");
			if(CommonUtils.isEmpty(startNum)){
				startNum = "0";
			}
			pm.setPageSize(Integer.valueOf(pageSize));
			pm.setStartNum(Integer.valueOf(startNum));
			try {
				list = sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PROCEDURE_ALL_INFO, pm);
//				List<Map<String, Object>> list = procedureService.queryProcedureNum(reqMap);
				result.setContent(Constants.SUCCESS, null);
				
			} catch (Exception e){
				result.setContent(Constants.FAIL, e.getMessage());
			}
			
		} 
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("dataList", list);
		map.put("totleRows",pm.getTotalRecord());
		result.setData(map);
		rtnMap.put("data", result.getContent());
	}
	
	
	/**
	 * 获取员工对应工序数量
	 * @param request
	 * @param response
	 * @param rtnMap
	 * @throws ServiceException
	 * @throws ParamerException
	 */
	public void getUserProceNum(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		User user = SessionUtils.getUserInfo(request);
		if(!CommonUtils.isEmpty(param.get("PRO_ID"))&&!CommonUtils.isEmpty(user.getUser_id())){
			reqMap.putAll(param);
			if(Constants.ADMIN_CODE.equals(user.getType())){
				//管理员用户登录时，根据user_id查
				String user_id = request.getParameter("USER_ID");
				if(!CommonUtils.isEmpty(user_id)){
					reqMap.put("USER_ID", user_id);
				} else{
					
				}
			} else{
				//非管理员用户则根据当前用户查询
				reqMap.put("USER_ID", user.getUser_id());
			}
			
			try {
				List<Map<String, Object>> list = sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_PROCEDURE_NUM, reqMap);
//				List<Map<String, Object>> list = procedureService.queryProcedureNum(reqMap);
				result.setContent(Constants.SUCCESS, null,list);
			} catch (Exception e){
				result.setContent(Constants.FAIL, e.getMessage());
			}
			
		} else{
			throw new ParamerException("Parameter[PRO_ID] is empty, please check it!");
		}
		
		
		rtnMap.put("data", result.getContent());
	}
	
	/**
	 * 添加员工工序记录
	 * @param request
	 * @param response
	 * @param rtnMap
	 * @throws ServiceException
	 * @throws ParamerException
	 */
	public void addUserProce(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		if(!CommonUtils.isEmpty(param.get("PRO_ID"))&&!CommonUtils.isEmpty(param.get("PROD_ID"))
				&&!CommonUtils.isEmpty(param.get("NUM"))&&!CommonUtils.isEmpty(SessionUtils.getUserInfo(request).getUser_id())){
			reqMap.putAll(param);
			User user = SessionUtils.getUserInfo(request);
			reqMap.put("CREATE_USER", user.getUser_id());
			reqMap.put("STATUS_CD", "1001");
			if(CommonUtils.isEmpty(param.get("USER_ID"))){
				//当前端参数为空时，user_id取当前登录用户
				reqMap.put("USER_ID", user.getUser_id());
			}
			try {
				int n =procedureService.insertUserProcedure(reqMap);
				if(n>0){
					result.setContent(Constants.SUCCESS, "员工工序录入成功");
				} else if(n ==-2){
					result.setContent(Constants.FAIL, "员工该工序明细已存在");
				} else {
					result.setContent(Constants.FAIL, "员工工序录入失败");
				}
			} catch (ServiceException e) {
				result.setContent(Constants.FAIL, e.getMessage());
				throw new ServiceException(this.getClass().toString()+" \n ->"+e.getMessage(),e);
			} catch (Exception e){
				result.setContent(Constants.FAIL, e.getMessage());
			}
			
			
		} else{
			throw new ParamerException("Parameter[PROD_ID/PRO_ID/NUM] is empty, please check it!");
		}
		
		rtnMap.put("data", result.getContent());
	}
	
	public void getStaffUser(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
//		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		User user = SessionUtils.getUserInfo(request);
		if(!CommonUtils.isEmpty(user.getUser_id())){
			if(Constants.STAFF_CODE.equals(user.getType())){
				reqMap.put("USER_ID", user.getUser_id());
			}
			try {
				reqMap.put("TYPE", Constants.STAFF_CODE);
				List<Map<String, Object>> list = sqlSessionDaoSupport.getSqlSession().selectList(ServiceConstants.QUERY_USER, reqMap);
//					LoginService loginService =  (LoginService)getService(request,"loginService");
//					List<Map<String, Object>> list = loginService.queryUser(reqMap);
				result.setContent(Constants.SUCCESS, null,list);
			} catch (Exception e){
				result.setContent(Constants.FAIL, e.getMessage());
			}
			
		} else{
			throw new ParamerException("Parameter[USER_ID] is empty, please check it!");
		}
		
		
		rtnMap.put("data", result.getContent());
	}
	
	public void updateProcedureNum(HttpServletRequest request,HttpServletResponse response,Map<String, Object> rtnMap) throws ServiceException, ParamerException{	
		ReturnResult result = new ReturnResult();
		Map<String, Object> param = Utility.Params.parseParams(request);
		Map<String,Object> reqMap = new HashMap<String, Object>();
		User user = SessionUtils.getUserInfo(request);
		Object oper_type = param.get("oper_type");
		if(!CommonUtils.isEmpty(user.getUser_id())&&!CommonUtils.isEmpty(param.get("status_cd"))
				&&!CommonUtils.isEmpty(oper_type)&&!CommonUtils.isEmpty(param.get("prod_id"))
				&&!CommonUtils.isEmpty(param.get("proc_id"))&&!CommonUtils.isEmpty(param.get("user_id"))){
			reqMap.put("UPDATE_USER", user.getUser_id());
			reqMap.put("STATUS_CD", param.get("status_cd"));
			reqMap.put("PROD_ID", param.get("prod_id"));
			reqMap.put("PRO_ID", param.get("proc_id"));
			reqMap.put("USER_ID", param.get("user_id"));
			boolean flag = true;
			if("modify".equals(oper_type.toString())){
				if(CommonUtils.isEmpty(param.get("num"))){
					flag = false;
				} else{
					reqMap.put("NUM", param.get("num"));
				}
			} 
			reqMap.put("oper_type", oper_type);
			if(flag){
				try {
					int count = 0;
					if("del".equals(oper_type.toString())){
						count = procedureService.deleteProcedureNum(reqMap);
					} else if("modify".equals(oper_type.toString())){
						count = procedureService.modifyProcedureNum(reqMap);
					} else if("pass".equals(oper_type.toString())){
						count = procedureService.passProcedureNum(reqMap);
					}
					if(count > 0)
						result.setContent(Constants.SUCCESS, null);
					else
						result.setContent(Constants.FAIL, null);
				} catch (ServiceException e) {
					result.setContent(Constants.FAIL, e.getMessage());
					throw new ServiceException(this.getClass().toString()+" \n ->"+e.getMessage(),e);
				} catch (Exception e){
					result.setContent(Constants.FAIL, e.getMessage());
				}
			} 
		} else{
			throw new ParamerException("Parameter[USER_ID] is empty, please check it!");
		}
		
		
		rtnMap.put("data", result.getContent());
	}
}
